<?php
class ControllerGrupos extends Controller {
	var $error = array();

	function index() {
		$response =& $this->locator->get('response');
		$template =& $this->locator->get('template'); 
		$module   =& $this->locator->get('module');

		$template->set('title', 'Grupos de Usuarios');

		$template->set('content', $this->getList());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function insert() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$template->set('title',  'Grupos de Usuarios');

		if (($request->isPost()) && ($this->validateForm())) {

		$sql = "insert into grupos set grupo = '?',descripcion ='?'";
			$database->query($database->parse($sql, $request->get('grupo', 'post'),$request->get('descripcion', 'post')));

			$altas = $request->get('altas', 'post', array());
			$bajas = $request->get('bajas', 'post', array());
			$modificaciones = $request->get('modificaciones', 'post', array());
			$consultas = $request->get('consultas', 'post', array());
			
		     foreach ($altas as $alta) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $alta,'A'));
	  		}

		     foreach ($bajas as $baja) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $baja,'B'));
	  		}
	  		
		     foreach ($modificaciones as $modificacion) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $modificacion,'M'));
	  		}

		     foreach ($consultas as $consulta) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $consulta,'C'));
	  		}
	  		
			$cache->delete('grupos');

			$session->set('message','Se ha actualizado la tabla de grupos');
						
			$response->redirect($url->ssl('grupos'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function update() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');

		$template->set('title', 'Grupos de Usuarios');

		if (($request->isPost()) && ($this->validateForm())) {

			$sql = "update grupos set descripcion = '?' where grupo = '?'";
			$database->query($database->parse($sql, $request->get('descripcion', 'post'), $request->get('grupo', 'post')));

			$database->query("delete from perfiles where grupo = '" . $request->get('grupo', 'post') . "'");

			$altas = $request->get('altas', 'post', array());
			$bajas = $request->get('bajas', 'post', array());
			$modificaciones = $request->get('modificaciones', 'post', array());
			$consultas = $request->get('consultas', 'post', array());
			
		     foreach ($altas as $alta) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $alta,'A'));
	  		}

		     foreach ($bajas as $baja) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $baja,'B'));
	  		}
	  		
		     foreach ($modificaciones as $modificacion) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $modificacion,'M'));
	  		}

		     foreach ($consultas as $consulta) {
        		$sql = "insert into perfiles set grupo = '?', formulario = '?', permiso='?'";
        		$database->query($database->parse($sql, $request->get('grupo', 'post'), $consulta,'C'));
	  		}
			
			
	  		$cache->delete('grupos');
			
			$session->set('message','Se ha actualizado la tabla de grupos');
			
			$response->redirect($url->ssl('grupos'));
		}

		$template->set('content', $this->getForm());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function delete() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$template =& $this->locator->get('template');
		$session  =& $this->locator->get('session');
		$module   =& $this->locator->get('module');
		$cache    =& $this->locator->get('cache');
 
		$template->set('title', 'Grupos de Usuarios');

		if (($request->get('loc_codigo')) && ($this->validateDelete())) {
			$database->query("delete from grupos where Grupo = '" . $request->get('grupo','get') . "'");
			$database->query("delete from perfiles where grupo = '" . $request->get('grupo', 'get') . "'");
			
			$cache->delete('grupos');
			
			$session->set('message','Se ha actualizado la tabla de grupos');
						
			$response->redirect($url->ssl('grupos'));
		}

		$template->set('content', $this->getList());

		$template->set($module->fetch());

		$response->set($template->fetch('layout.tpl'));
	}

	function getList() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$url      =& $this->locator->get('url');
		$session  =& $this->locator->get('session');
		$language =& $this->locator->get('language');
		$user  =& $this->locator->get('user');
		
		$cols = array();

		$cols[] = array(
			'name'  => 'Grupo',
			'sort'  => 'Grupo',
			'align' => 'left'
		);

		$cols[] = array(
			'name'  => 'Descripci&oacute;n',
			'sort'  => 'descripcion',
			'align' => 'left'
		);

    	$cols[] = array(
      		'name'  => 'Acciones',
      		'align' => 'right'
    	);
		
		if (!$session->get('grupos.search')) {
			$sql = "select Grupo, descripcion from grupos";
		} else {
			$sql = "select Grupo, descripcion from grupos where Grupo like '?' or descripcion like '?'";
		}

		$sort = array(
			'Grupo',
			'descripcion'
		);

		if (in_array($session->get('grupos.sort'), $sort)) {
			$sql .= " order by " . $session->get('grupos.sort') . " " . (($session->get('grupos.order') == 'desc') ? 'desc' : 'asc');
		} else {
			$sql .= " order by grupo asc";
		}

		$results = $database->getRows($database->splitQuery($database->parse($sql, '%' . $session->get('grupos.search') . '%','%' . $session->get('grupos.search') . '%'), $session->get('grupos.page'), $config->get('config_max_rows')));

		$rows = array();

		foreach ($results as $result) {
			$cell = array();

			$cell[] = array(
				'value'   => $result['Grupo'],
				'align'   => 'left',
				'default' => 0
			);

			$cell[] = array(
				'value'   => $result['descripcion'],
				'align'   => 'left',
				'default' => 0
			);

			$action = array();
      		
			if ($user->getPERMISOS($user->getPERSONA(),'grupos','M'))
			{
			$action[] = array(
        		'icon' => 'update.png',
				'text' => 'Modificar',
				'href' => $url->ssl('grupos', 'update', array('grupo' => $result['Grupo']))
      		);
			}
						
			if ($user->getPERMISOS($user->getPERSONA(),'grupos','B'))
			{
			$action[] = array(
        		'icon' => 'delete.png',
				'text' => 'Eliminar',
				'href' => $url->ssl('grupos', 'delete', array('grupo' => $result['Grupo']))
      		);
			}

      		$cell[] = array(
        		'action' => $action,
        		'align'  => 'right'
      		);
			
			$rows[] = array('cell' => $cell);
		}

		$view = $this->locator->create('template');

		$view->set('heading_title', 'Grupos');
		$view->set('heading_description', 'Gesti&oacute;n de Grupos de Usuarios');

		$view->set('text_default', $language->get('text_default'));
		$view->set('text_results', $language->get('text_results', $database->getFrom(), $database->getTo(), $database->getTotal()));

		$view->set('entry_page', $language->get('entry_page'));
		$view->set('entry_search', $language->get('entry_search'));
		$view->set('button_search', $language->get('button_search'));

		$view->set('button_list', $language->get('button_list'));
		$view->set('button_insert', $language->get('button_insert'));
		$view->set('button_exportar', $language->get('button_exportar'));

		$view->set('error', @$this->error['message']);

		$view->set('message', $session->get('message'));
		
		$session->delete('message');
		
		$view->set('action', $url->ssl('grupos', 'page'));

		$view->set('search', $session->get('grupos.search'));
		$view->set('sort', $session->get('grupos.sort'));
		$view->set('order', $session->get('grupos.order'));
		$view->set('page', $session->get('grupos.page'));
 
		$view->set('cols', $cols);
		$view->set('rows', $rows);

		$view->set('list', $url->ssl('grupos'));

		if ($user->getPERMISOS($user->getPERSONA(),'grupos','A'))
		{
		$view->set('insert', $url->ssl('grupos', 'insert'));
		}
		
		$view->set('export', 'index.php?controller=grupos');

		$view->set('titulo_ventana', '::. Exportar Grupos');

		$page_data = array();

		for ($i = 1; $i <= $database->getPages(); $i++) {
			$page_data[] = array(
				'text'  => $language->get('text_pages', $i, $database->getPages()),
				'value' => $i
			);
		}		

		$view->set('pages', $page_data);

		return $view->fetch('content/list.tpl');
	}

	function getForm() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');

		$view = $this->locator->create('template');

		$view->set('heading_title', 'Grupos de Usuarios');
		$view->set('heading_description', 'Gesti&oacute;n de grupos de usuarios');

		$view->set('entry_grupo', 'C&oacute;digo:');
		$view->set('entry_descripcion', 'Descripci&oacute;n:');
		$view->set('entry_alta', 'Alta');
		$view->set('entry_baja', 'Baja');
		$view->set('entry_modificacion', 'Modificaci&oacute;n');
		$view->set('entry_consulta', 'Consulta');

		$view->set('button_save', 'Guardar');
		$view->set('button_cancel', 'Cancelar');

		$view->set('error', @$this->error['message']);
		$view->set('error_grupo', @$this->error['grupo']);
		$view->set('error_descripcion', @$this->error['descripcion']);
		
		$view->set('tab_general', $language->get('tab_general'));

		$view->set('action', $url->ssl('grupos', $request->get('action'), array('grupos' => $request->get('grupos'))));
 
		$view->set('cancel', $url->ssl('grupos'));

		if (($request->get('grupo')) && (!$request->isPost())) {
			$consulta = "select distinct * from grupos where grupo = '" . $request->get('grupo') ."'";
			$grupo_info = $database->getRow($consulta);
		}

		if ($request->has('grupo', 'post')) {
			$view->set('grupo', $request->get('grupo', 'post'));
			$codigo_grupo =$request->get('grupo', 'post');
		} else {
			$view->set('grupo', @$grupo_info['grupo']);
			$codigo_grupo = @$grupo_info['grupo'];
		}

		if ($request->has('descripcion', 'post')) {
			$view->set('descripcion', $request->get('descripcion', 'post'));
		} else {
			$view->set('descripcion', @$grupo_info['descripcion']);
		}

		$permission_data = array();

		foreach (glob(DIR_CONTROLLER . '*') as $controller) {
			if (basename($controller, '.php') != 'module_admin_footer' && basename($controller, '.php') != 'module_admin_header' && basename($controller, '.php') != 'module_admin_menu' && basename($controller, '.php') != 'findlocalidad' && basename($controller, '.php') != 'findestablecimiento' && basename($controller, '.php') != 'findpersona' && basename($controller, '.php') != 'home' && basename($controller, '.php') != 'login' && basename($controller, '.php') != 'logout' && basename($controller, '.php') != 'password')
			{
 				$permisoA = $database->getRow("select * from perfiles where grupo = '" . $codigo_grupo . "' and formulario = '" . basename($controller, '.php') . "' and permiso='A'");
 				$permisoB = $database->getRow("select * from perfiles where grupo = '" . $codigo_grupo . "' and formulario = '" . basename($controller, '.php') . "' and permiso='B'");
 				$permisoM = $database->getRow("select * from perfiles where grupo = '" . $codigo_grupo . "' and formulario = '" . basename($controller, '.php') . "' and permiso='M'");
 				$permisoC = $database->getRow("select * from perfiles where grupo = '" . $codigo_grupo . "' and formulario = '" . basename($controller, '.php') . "' and permiso='C'");
				
				$permission_data[] = array(
					'name'   => basename($controller, '.php'),
					'alta'  => (isset($permisoA) ? $permisoA : in_array('A', $request->get('permissions', 'post', array()))),
					'baja'  => (isset($permisoB) ? $permisoB : in_array('B', $request->get('permissions', 'post', array()))),
					'modificacion'  => (isset($permisoM) ? $permisoM : in_array('M', $request->get('permissions', 'post', array()))),
					'consulta'  => (isset($permisoC) ? $permisoC : in_array('C', $request->get('permissions', 'post', array()))),				
			);
			}
		}
		$view->set('permissions', $permission_data);
		
	
		return $view->fetch('content/grupos.tpl');
	}

	function validateForm() {
		$request  =& $this->locator->get('request');
		$user     =& $this->locator->get('user');
		$language =& $this->locator->get('language');

			if ((strlen($request->get('grupo', 'post')) == 0)) {
			$this->error['grupo'] = 'Debe ingresar un c&oacute;digo de grupo';
		}
		if ((strlen($request->get('descripcion', 'post')) < 1) || (strlen($request->get('grupo', 'post')) > 50)) {
			$this->error['descripcion'] = 'La descripci&oacute;n ingresada debe ser mayor que 0 caracteres y menor que 50';
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function validateDelete() {
		$request  =& $this->locator->get('request');
		$database =& $this->locator->get('database');
		$config   =& $this->locator->get('config');
		$user     =& $this->locator->get('user');
		$language =& $this->locator->get('language');

		//if (!$user->hasPermission('modify', 'localidad')) {
		//	$this->error['message'] = $language->get('error_permission');
		//}

		$personagrupos_info = $database->getRow("select count(*) as total from personasgrupos where grupos = '" . $request->get('grupo') . "'");
		if ($personagrupos_info['total']) {
			$this->error['message'] = 'No es posible eliminar el grupo'; // si contiene: ' . $personagrupos_info['total']) . ' personas asociadas';
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function page() {
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$url      =& $this->locator->get('url');
		$session  =& $this->locator->get('session');

		if ($request->has('search', 'post')) {
			$session->set('grupos.search', $request->get('search', 'post'));
		}

		if (($request->has('page', 'post')) || ($request->has('search', 'post'))) {
			$session->set('grupos.page', $request->get('page', 'post'));
		}

		if ($request->has('sort', 'post')) {
			$session->set('grupos.order', (($session->get('grupos.sort') == $request->get('sort', 'post')) && ($session->get('grupos.order') == 'asc')) ? 'desc' : 'asc');
		}

		if ($request->has('sort', 'post')) {
			$session->set('grupos.sort', $request->get('sort', 'post'));
		}

		$response->redirect($url->ssl('grupos'));
	}	

}
?>
